package streamobject

import (
	"github.com/pkg/errors"
	"yizhuoyan/go-study/pdfgo/handyio"
	"yizhuoyan/go-study/pdfgo/raw/objects"
	"yizhuoyan/go-study/pdfgo/raw/objects/basicobject"
)

const typeNameOfObjStm = "/ObjStm"

type ObjectStreamComponent struct {
	N          int                                  `#:"(Required) The number of compressed objects in the stream."`
	First      int                                  `#:"(Required) The byte offset of the first compressed object"`
	Extends    *basicobject.IndirectObjectReference `#:"(Optional) A reference to an parent object stream,"`
	objects    []objects.Object
	dictionary *basicobject.Dictionary `#:"包含的dictionary"`
}

func (this *ObjectStreamComponent) GetType() string {
	return typeNameOfObjStm
}

func NewObjectStream() *ObjectStreamComponent {
	return &ObjectStreamComponent{
		N:          0,
		First:      0,
		Extends:    nil,
		objects:    nil,
		dictionary: basicobject.NewDictionary(),
	}
}
func (this *ObjectStreamComponent) Put(key string, value basicobject.BasicObject) basicobject.BasicObject {
	return this.dictionary.Put(key, value)
}
func (this *ObjectStreamComponent) Serialize(w handyio.PdfRawWriter) error {
	var fieldDic = this.dictionary
	fieldDic.Put("/Type", basicobject.NewName(typeNameOfObjStm))
	fieldDic.Put("/N", basicobject.NewInteger(this.N))
	fieldDic.Put("/First", basicobject.NewInteger(this.First))
	if this.Extends != nil {
		fieldDic.Put("/Extends", this.Extends)
	}
	if err := fieldDic.Serialize(w); err != nil {
		return err
	}
	w.WriteBytes(StartStreamKeywordBytes)
	//输出objects
	for _, one := range this.objects {
		if err := one.Serialize(w); err != nil {
			return errors.Wrapf(err, "Write ObjectStreamComponent")
		}
	}
	w.WriteBytes(EndStreamKeywordBytes)

	return nil

}

func (this *ObjectStreamComponent) UnSerialize(r handyio.PdfRawReader) error {
	//TODO implement me
	panic("implement me")
}
func (this *ObjectStreamComponent) GetDictionary() *basicobject.Dictionary {
	return this.dictionary
}

func (this *ObjectStreamComponent) ReadStream(dic *basicobject.Dictionary, r handyio.PdfRawReader) error {
	return nil
}
